package com.kcsj.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.IOException;
import java.util.Calendar;
/**
 * @author 胡庆阳
 * 29th Nov. 2020
 */
public class TokenHelper {
    public static final String SING = "!@234%U?H23";
     public static String getToken(JWTResult jwtResult){
         //添加Token过期时间
         Calendar instance = Calendar.getInstance();
         instance.add(Calendar.MINUTE,30);
         //instance.add(Calendar.SECOND,15);
         //添加构成JWT的参数
         String token = JWT.create()
                 .withClaim("username", jwtResult.getUsername())//payload荷载信息,实际数据
                 .withClaim("roleName", jwtResult.getRoleName())
                 .withClaim("userId", jwtResult.getUserId())
                 //.withClaim("salt", Math.random()*1000)
                 .withExpiresAt(instance.getTime()) //指定令牌的过期时间
                 .sign(Algorithm.HMAC256(SING));//签名 由头信息+荷载信息+密钥 组合之后进行加密得到
         return token;
     }

    public static String getFlushToken(JWTResult jwtResult) {
        Calendar instance = Calendar.getInstance();
        //instance.add(Calendar.SECOND,40);
        instance.add(Calendar.MINUTE, 10); //默认7天过期
        //添加构成JWT的参数
        String token = JWT.create()
                .withClaim("username", jwtResult.getUsername())//payload荷载信息,实际数据
                .withClaim("roleName", jwtResult.getRoleName())
                .withClaim("userId", jwtResult.getUserId())
                //.withClaim("salt", Math.random()*1000)
                .withExpiresAt(instance.getTime()) //指定令牌的过期时间
                .sign(Algorithm.HMAC256(SING));//签名 由头信息+荷载信息+密钥 组合之后进行加密得到
        return token;
    }

    public static JWTResult verify(String token) throws IOException {
        //创建验证对象
        DecodedJWT verify =
                JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        //解码对象
        String username = verify.getClaim("username").asString();
        String roleName = verify.getClaim("roleName").asString();
        Integer userId = verify.getClaim("userId").asInt();
        JWTResult jwtResult = new JWTResult(userId, username, roleName);
        return jwtResult;
    }
}
